package com.kchouse.mine;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.MineCarItem;
import com.kchouse.bean.MinePrestoreItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;

import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class MineCarActivity extends BaseActivity implements OnClickListener {

    private TextView tv_title;
    private ImageView iv_back;
    private ListView lv_item;
    private ImageView iv_add;
    private Intent intent;
    private MineCarActivity mContent;
    private ArrayList<MineCarItem>listcar=new ArrayList<>();
    private CarAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_car);
        mContent = this;
        intiData();
        intiView();

    }

    private void intiData() {
        intent = getIntent();
    }

    @Override
    protected void onResume() {
        super.onResume();

        GetMineCar();
    }

    /**
     * 获取我的车辆列表
     */
    private void GetMineCar() {
        String url = API.GetMineCar + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    listcar.clear();
                    listcar.addAll(JSONObject.parseArray(data.getString("carList"), MineCarItem.class));
                    if(listcar.size()>2)
                    {
                        iv_add.setVisibility(View.GONE);
                    }else {
                        iv_add.setVisibility(View.VISIBLE);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("我的车辆");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        lv_item = (ListView) findViewById(R.id.lv_item);
       adapter= new CarAdapter();
        lv_item.setAdapter(adapter);
        iv_add = (ImageView) findViewById(R.id.iv_add);
        iv_add.setOnClickListener(this);
    }

    class CarAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listcar.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MineCarItem item = listcar.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_minecar_item, null);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            tv_name.setText(item.getCarNumber());
            TextView tv_del = (TextView) view.findViewById(R.id.tv_del);
            tv_del.setOnClickListener(new DelOnClidk(position));
            return view;
        }
    }

    class DelOnClidk implements OnClickListener{

        private  int pos;

        public DelOnClidk(int pos){

            this.pos=pos;
        }
        @Override
        public void onClick(View v) {
            MineCarItem item = listcar.get(pos);
            showNormalDialog(item.getId());
        }
    }

    private void showNormalDialog(final String id){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(mContent);
        normalDialog.setTitle("确认删除该车辆？");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DelCar(id);
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        // 显示
        normalDialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_add:
                checkidentity();
                break;
        }
    }


    /**
     * 移除我的车辆
     */
    private void DelCar(String id) {
        String url = API.DelCar + id;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("id", id);
//        params.addFormDataPart("type", publishType);
        HttpRequest.delete(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    ToastUtils.getInstanc(mContent).showToast("删除成功");

                    GetMineCar();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 确定汽车身份
     */
    private void checkidentity() {
        // 创建构建器
        AlertDialog.Builder builder = new AlertDialog.Builder(mContent);
        // 设置参数
        builder.setTitle("是否是新能源汽车").setPositiveButton("是", new DialogInterface.OnClickListener() {// 积极

            @Override
            public void onClick(DialogInterface dialog,
                                int which) {
                intent.putExtra("isNew",true);
                intent.setClass(mContent, NewMineCarActivity.class);
                startActivity(intent);
            }
        }).setNegativeButton("不是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                intent.putExtra("isNew",false);
                intent.setClass(mContent, NewMineCarActivity.class);
                startActivity(intent);
            }
        });
        builder.create().show();
    }

}
